package com.cuts.videoedit.widget

import android.widget.BaseAdapter
import android.widget.FrameLayout
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cuts.videoedit.R
import com.cuts.videoedit.data.VideoFrameData
import com.cuts.videoedit.helper.DecodeFrameListener
import com.cuts.videoedit.helper.IAvFrameHelper
import kotlin.times

class VideoFrameAdapter (data: MutableList<VideoFrameData>,
                         private val frameWidth: Int):
    BaseQuickAdapter<VideoFrameData,
            BaseViewHolder>(R.layout.item_video_frame, data) {
    private var avframeHelper:IAvFrameHelper? = null
    private var index = 0



    fun setAvframeHelper(avframeHelper: IAvFrameHelper) {
        this.avframeHelper = avframeHelper
        avframeHelper.decodeFrameListener =object : DecodeFrameListener{
            override fun onGetOneFrame() {
               notifyDataSetChanged()
            }
        }
    }
    override fun convert(
        holder: BaseViewHolder,
        item: VideoFrameData)
    {
        val imageView=holder.getView<ImageView>(R.id.iv)
        val layoutParams = holder.itemView.layoutParams
        layoutParams.width = item.frameWidth

        val ivLayoutParams = imageView.layoutParams as FrameLayout.LayoutParams
        imageView.tag = holder.adapterPosition
        avframeHelper?.loadAvFrame(imageView,item.frameClipTime * 1000)

        avframeHelper?.let {
            Glide.with(imageView)
                .asBitmap()
                .load(item.videoData.originalFilePath)
                .frame(item.frameClipTime * 1000)
                .thumbnail(
                    //todo 更好的方案是往前找一个已经有的缓存帧
                    Glide.with(imageView).asBitmap().load(item.videoData.originalFilePath)
                )
                .into(imageView)


        }
    }

    fun getAvframeHelper():IAvFrameHelper?{
        return avframeHelper
    }
}